<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;

class Links extends Allow
{
    public function getindex()
    {
        // 获取链接列表
        $links=Db::table("links")->select();
        // var_dump($links);
    	//加载链接列表模板
    	return $this->fetch("Links/index",['links'=>$links]);
    }

    // //添加
    public function getadd(){
        //加载链接添加模板
        return $this->fetch("Links/add");
    }

    //执行添加
    public function postinsert(){
        // echo '1';
        $request=request();
        //获取链接名称和链接地址
        $row=$request->only(['linksname','linksaddress']);
        // var_dump($row);exit;
        if($row['linksname']&&$row['linksaddress']){
             if(Db::table("links")->insert($row)){
                $this->success("友情链接添加成功","/adminlinks/index");
            }else{
                $this->error("友情链接添加失败","/adminlinks/add");
            }
        }else{$this->error("链接名称和链接地址不能为空,请重新添加");}
    }
    //删除
    public function getdelete(){
        $request=request();
        //获取id
        $id=$request->param('id');
        if(Db::table('links')->where('id',"{$id}")->delete()){
            $this->success("删除成功","/adminlinks/index");
        }else{
            $this->error("删除失败","/adminlinks/index");
        }
    }
    //变换状态
    public  function getstatus(){
        $request=request();
        //获取id
        $data=$request->only(['id','status']);
        $id = $data['id'];
        $status = $data['status'];
        //判断连接状态
        if($status=='0'){
            $status='1';
        }else{
            $status='0';
        }
        // var_dump($id);
        // var_dump($status);
        if(Db::execute("update links set status='{$status}' where id='{$id}'")){
            $this->redirect("/adminlinks/index");
        }else{
            $this->error("/adminlinks/index");
        }
    }

    //编辑
    public function getedit(){
        $request=request();
        //获取id
        $id=$request->param('id');
        // var_dump($id);
        $result = Db::query("select * from links where id={$id}");
        $res = $result['0'];
        return $this->fetch("Links/edit",['res'=>$res]);
    }
    //执行编辑操作
    public  function postupdate(){
        $request=request();
        //获取id
        $data=$request->only(['id','linksname','linksaddress','status']);
        // var_dump($data);
        $id = $data['id'];
        $linksname = $data['linksname'];
        $linksaddress = $data['linksaddress'];
        $status = $data['status'];
        if($linksname&&$linksaddress){
            //执行更新
            if(Db::execute("update links set linksname='{$linksname}',linksaddress='{$linksaddress}',status='{$status}' where id='{$id}'")){
                $this->redirect("/adminlinks/index");
            }else{
                $this->error("/adminlinks/index");
            }
        }else{$this->error("链接名称和链接地址不能为空,请重新编辑");}
    }
}
